import os
import logging
import json
import time
from datetime import datetime
from logging.handlers import TimedRotatingFileHandler
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_START_TIMESTAMP = int(time.time())
PROJECT_NAME = "xcnvs"
PROJECT_VERSION = "0.01"

class Settings(object):
    def __init__(self, filepath):
        self.__filepath = filepath

        settings_data = None
        for encoding in ["utf-8", "gbk"]:
            try:
                f = open(filepath, 'r', encoding=encoding)
                content = f.read()
                settings_data = json.loads(content)
                f.close()
                break
            except Exception as e:
                print("Settings.__init__() error:%s,encoding=%s|%s" % (str(e), encoding, str(filepath)))

        if settings_data:
            self.__settings_data = settings_data
            self.__settings_data_str = str(settings_data)

            self.ip = settings_data.get("ip")
            self.port = int(settings_data.get("port"))
            self.debug = bool(settings_data.get("debug",False))
            self.logDebug = bool(settings_data.get("logDebug",False))
            self.logDay = int(settings_data.get("logDay",7))

        else:
            msg = "read Settings %s error" % str(filepath)
            raise Exception(msg)

    def __del__(self):
        pass

    def getStr(self):
        return self.__settings_data_str

__log_dir = os.path.join(BASE_DIR, 'log')
if not os.path.exists(__log_dir):
    os.makedirs(__log_dir)
g_settings = Settings(filepath=os.path.join(BASE_DIR, "settings.json"))
def CreateLogger(logDir, is_show_console=False):
    if not os.path.exists(logDir):
        os.makedirs(logDir)

    LOGGER_TIMEFMT = "%Y%m%d-%H%M%S"
    LOGGER_WHEN = 'd'
    LOGFILE_BACKUPCOUNT = g_settings.logDay

    fileName = os.path.join(logDir, "%s.log" % (datetime.now().strftime(LOGGER_TIMEFMT)))
    if g_settings.logDebug:
        level = logging.DEBUG
    else:
        level = logging.INFO
    logger = logging.getLogger()
    logger.setLevel(level)
    formatter = logging.Formatter('%(asctime)s %(name)s %(lineno)s %(levelname)s %(message)s')

    # 最基础
    # fileHandler = logging.FileHandler(fileName, encoding='utf-8')  # 指定utf-8格式编码，避免输出的日志文本乱码
    # fileHandler.setLevel(level)
    # fileHandler.setFormatter(formatter)
    # logger.addHandler(fileHandler)

    # 时间滚动切分
    # when:备份的时间单位，backupCount:备份保存的时间长度
    timedRotatingFileHandler = TimedRotatingFileHandler(fileName,
                                                        when=LOGGER_WHEN,
                                                        backupCount=LOGFILE_BACKUPCOUNT,
                                                        encoding='utf-8')

    timedRotatingFileHandler.setLevel(level)
    timedRotatingFileHandler.setFormatter(formatter)
    logger.addHandler(timedRotatingFileHandler)

    # 控制台打印
    if is_show_console:
        streamHandler = logging.StreamHandler()
        streamHandler.setLevel(level)
        streamHandler.setFormatter(formatter)
        logger.addHandler(streamHandler)

    return logger
g_logger = CreateLogger(logDir=__log_dir, is_show_console=True)
g_logger.info("%s v%s built on 2024/11/08" % (PROJECT_NAME,PROJECT_VERSION))
g_logger.info("BASE_DIR=%s,PROJECT_START_TIMESTAMP=%d" % (BASE_DIR,PROJECT_START_TIMESTAMP))
